<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
    public function index(){
        if(!empty($_REQUEST['echostr'])){
            echo $_REQUEST['echostr'];//Token验证 直接输出
        }else{
            //接收用户发送过来的消息
            $strData =  $GLOBALS["HTTP_RAW_POST_DATA"];//接收到xml数据
            if(!empty($strData)){
                $obj = simplexml_load_string($strData);//把xml字符串解析成对象
               if($obj->MsgType=="text"){//收到文本消息
                    $this->dealCommonData($obj->Content,$obj->FromUserName,$obj->ToUserName);
                }else if($obj->MsgType=="image"){//收到图片
                   $this->dealCommonDataimg($obj->FromUserName,$obj->ToUserName);
               }else if($obj->MsgType=="event"){
                   if($obj->Event=="subscribe"){//订阅
                       $this->dealCommonSubscribe($obj->Event,$obj->FromUserName,$obj->ToUserName);
                   }else if(isset($obj->EventKey)){
                       $this->dealCommonData($obj->Event,$obj->FromUserName,$obj->ToUserName,$obj->EventKey);
                   }
                }else{

                }
            }
        }
    }

    public function dealCommonSubscribe($Event,$openId,$toUserName){//订阅
        $strData =C('text');
        echo sprintf($strData,$openId,$toUserName,time(),"
感谢你的关注。
终于等到你来了，
我是您的私人助理——“小知”。
有事就大声呼叫小知吧。

【小知推荐】
<a href='http://wx1.zmweb.top/zhiming/index.php/home-bzjp-index'>1.2020年你的运势如何？</a>
<a href='http://wx1.zmweb.top/zhiming/index.php/home-bzhh-index'>2.你们是注定的缘分吗？</a>
<a href='http://wx1.zmweb.top/zhiming/index.php/home-xmcs-index'>3.你的名字决定你是怎么样的人？</a>
<a href='http://wx1.zmweb.top/zhiming/index.php/home-bzcy-index'>4.你的财运是在哪个方向？</a>
<a href='http://wx1.zmweb.top/zhiming/index.php/home-bzsy-index'>5.事业受阻是什么原因导致造成的？</a>
<a href='http://wx1.zmweb.top/zhiming/index.php/Home-Mrys-index'>6.你今天看自己的运势分析了吗？</a>
<a href='http://wx1.zmweb.top/gzh/mingli/Public/images/img_gxqm.png'>7.免费设计个性签名（热门）</a>
");

        //<a href='http://wx1.zmweb.top/zhiming/index.php/Home-Index-openid?HDurl=http://sm.ddznzj.com/sm/selfhtml/regzmml'>8.领取金币</a>


//        $getToken=getToken();
//        $imgFile=mb_substr(THINK_PATH,0,-9)."Public/images/public/weixin0512.jpg";//双旦活动图片
//        $img=$this->uploadImg($getToken,$imgFile,'weixin0512');
//        $this->KFreplyImg($openId,$getToken,$img);
    }

    public function dealCommonData($text,$openId,$toUserName,$key=null){
        if($text=="CLICK"){
            $text=$key;
        }
        //普通回复
        $strData =C('text');
        $pdData=M()->query("select * from gzh_mingli where openid='{$openId}'");
        if($text=="测试"){
            echo sprintf($strData,$openId,$toUserName,time(),"测试");
        }else if($text=="招财"){
            $title1='12生肖招财聚财的小妙招，非常灵验';$description1='12生肖招财聚财的小妙招，非常灵验';$picurl='http://wx1.zmweb.top/gzh/mingli/Public/images/public/zhaocai.png';$url='https://mp.weixin.qq.com/s/x47yNKm0rewMB6QbquceKg';
            $this->replyImgText($openId,$toUserName,$title1,$description1,$picurl,$url);
        }else if($text=="养生"||$text=="生肖"||$text=="2020"||$text=="改运"||$text=="姻缘"||$text=="命运"||$text=="手机"||$text=="生日"){
            $this->replyText1($strData,$openId,$toUserName,time(),$text);

        } else if(($text=="结束" || $text=="退出")&&$pdData[0]['number']>=1){//退出艺术签名
            echo sprintf($strData,$openId,$toUserName,time(),"退出艺术签名");
            M()->query("update gzh_mingli set number=0 where openid='{$openId}'");
        } else if($text=="个性签名"&&$pdData[0]['number']<1){
             if(empty($pdData)){
                 M()->query("insert into gzh_mingli (openid,number)values('{$openId}',1)");
             }else{
                 M()->query("update gzh_mingli set number=1 where openid='{$openId}'");
             }
            echo sprintf($strData,$openId,$toUserName,time(),"免费艺术签名：\n请留下您的姓名\n领到签名后记得分享到朋友圈哦！");
        }else if($pdData[0]['number']==1){
            $str=mb_strlen($text);
            if(($str/3)>18){
                echo sprintf($strData,$openId,$toUserName,time(),"姓名过长，请重新输入。");exit;
            }
            $getToken=getToken();
            echo sprintf($strData,$openId,$toUserName,time(),"亲，已收到您的名字，\n分享朋友圈之后截图给我，我再给你设计另一种风格\n注：如有问题请输入‘退出’或者‘结束’");
            $img=$this->sucai($text,$getToken,905);
            $this->KFreplyImg($openId,$getToken,$img);
            M()->query("update gzh_mingli set name='{$text}',number=2 where openid='{$openId}'");
        }else if($pdData[0]['number']==2){
            echo sprintf($strData,$openId,$toUserName,time(),"请发送正确分享图片!获取第二种签名");
        } else{
            $strData=<<<BEGIN
              <xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[transfer_customer_service]]></MsgType>
                </xml>
BEGIN;
            echo sprintf($strData,$openId,$toUserName,time());
        }
    }
    public function dealCommonDataimg($openId,$toUserName){//收到图片回复
        $strData =C('text');
        $pdData=M()->query("select * from gzh_mingli where openid='{$openId}'");
        if($pdData[0]['number']==2){
            $getToken=getToken();
            echo sprintf($strData,$openId,$toUserName,time(),"这是你第二个签名，希望你喜欢");
            $img=$this->sucai($pdData[0]['name'],$getToken,901);
            $this->KFreplyImg($openId,$getToken,$img);
            M()->query("update gzh_mingli set number=0 where openid='{$openId}'");
        }
    }

    public function KFreply($openId,$getToken){//主动回复文本消息
        $url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$getToken}";
        $strData=array("touser"=>"{$openId}",
            "msgtype"=>"text",
            "text"=>array("content"=>"Hello World"),
        );
        $json=json_encode($strData,JSON_UNESCAPED_UNICODE);

        curl($url,$json);

    }
    public function KFreplyImg($openId,$getToken,$img){//主动回复图片消息
        $url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$getToken}";
        $strData=array("touser"=>"{$openId}",
            "msgtype"=>"image",
            "image"=>array("media_id"=>"{$img}"),
        );
        $json=json_encode($strData,JSON_UNESCAPED_UNICODE);

        curl($url,$json);
    }
    public function replyImgText($openId,$toUserName,$title1,$description1,$picurl,$url){//回复图文消息
        $strData=<<<BEGIN
          <xml>
              <ToUserName><![CDATA[%s]]></ToUserName>
              <FromUserName><![CDATA[%s]]></FromUserName>
              <CreateTime>%s</CreateTime>
              <MsgType><![CDATA[news]]></MsgType>
              <ArticleCount>1</ArticleCount>
              <Articles>
                <item>
                  <Title><![CDATA[%s]]></Title>
                  <Description><![CDATA[%s]]></Description>
                  <PicUrl><![CDATA[%s]]></PicUrl>
                  <Url><![CDATA[%s]]></Url>
                </item>
              </Articles>
          </xml>
BEGIN;
        echo sprintf($strData,$openId,$toUserName,time(),$title1,$description1,$picurl,$url);
    }
    public function replyText1($strData,$openId,$toUserName,$time,$text){
        switch($text){
            case '养生';$textdata='百岁老中医秘密透露的养生秘诀，多少钱都买不到这张表！';$url='https://mp.weixin.qq.com/s?__biz=MzU3MTM3MDc4OQ==&mid=2247485766&idx=4&sn=96ceb26f8a39ce319158bbabe0155c09&chksm=fce0750ccb97fc1ad6a09af080706aff48f0f79a744a66cf1bdcd47f783c871b0a2064688c5e&token=1256252977&lang=zh_CN#rd';break;
            case '生肖';$textdata='十二生肖，属什么最好命？';$url='https://mp.weixin.qq.com/s?__biz=MzA3NjEyMTkyNw==&mid=2651713581&idx=3&sn=e625e98eeedeca667afb72664a4b5839&chksm=849f4205b3e8cb130c5a7063570602959344223f52a95c02e9ca44edfd11a579e5a2ad0d2124&token=457694834&lang=zh_CN#rd';break;
            case '2020';$textdata='大师全面分析您的2020年运势大全！';$url='http://wx1.zmweb.top/zhiming/index.php/home-lnyc2020-index?channel=gzh001';break;
            case '改运';$textdata='绝密！12生肖改命方法，早看早好命~';$url='https://mp.weixin.qq.com/s?__biz=MzA3NjEyMTkyNw==&mid=2651713817&idx=8&sn=f658b0e7f42f7b9b6bbd2196b486439c&chksm=849f4331b3e8ca27be4c62d98e8dc191b8383d3acbd930f0bed354db1efe1f91dad7462058ad&token=457694834&lang=zh_CN#rd';break;
            case '婚缘';$textdata='招桃花、旺姻缘，最好的吉祥物原来是它？';$url='https://mp.weixin.qq.com/s?__biz=MzA3NjEyMTkyNw==&mid=2651713702&idx=5&sn=3199d1976277b177b01ce5771e21e97a&chksm=849f428eb3e8cb982ffc5c3a29a8c734843bf6bb1f7ce459bd387bdc37fb2ee094876149bf23&token=457694834&lang=zh_CN#rd';break;
            case '命运';$textdata='揭秘12生肖一生命运，神准';$url='https://mp.weixin.qq.com/s?__biz=MzA3NjEyMTkyNw==&mid=2651713702&idx=7&sn=8b70981f37032dee30510828e024b2f8&chksm=849f428eb3e8cb982a741d8840834ed08ec59b5a8ba73f9c4a2c8fc150a3c0d68ef27a928d8a&token=457694834&lang=zh_CN#rd';break;
            case '手机';$textdata='你的手机尾数是多少，就有多大财！';$url='https://mp.weixin.qq.com/s?__biz=MzA3NjEyMTkyNw==&mid=2651713675&idx=3&sn=4d18de407de4b4e37dc8692897ef45d7&chksm=849f42a3b3e8cbb503dd07e05b06aecc7173c1b6725a964cf14d1b8843af25e23f16c559df00&token=457694834&lang=zh_CN#rd';break;
            case '生日';$textdata='你的生日尾数是多少，就有多大财！';$url='https://mp.weixin.qq.com/s?__biz=MzA3NjEyMTkyNw==&mid=2651713399&idx=3&sn=46de957e6bbbfe092a7c075ad19ccc3a&chksm=849f5d5fb3e8d449ca8f5e810ce106d2c20a9b02006c031b3808147a7786d929008ed020a0cd&token=457694834&lang=zh_CN#rd';break;
            default;
        }
        echo sprintf($strData,$openId,$toUserName,time(),"<a href='{$url}'>{$textdata}</a>");
    }

    public function sucai($name,$getToken,$number){
        $yibiart=yibiArt("{$name}",$number);//一笔艺术签名
        $new_file = mb_substr(THINK_PATH,0,-9).'Upload/'.date("Y-m").'/';
        if(!is_dir($new_file)){//检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($new_file);
            chmod($new_file,0777);
        }
        $file=downloadImg($yibiart,$new_file);
        //$file="/opt/www/gzh/mingli/Upload/2018-05/1285.gif";
        $file=mergeImg($file,$name);//图片合成

        $strData=array(
            'media'=>'@'.$file
        );
        $url="https://api.weixin.qq.com/cgi-bin/media/upload?access_token={$getToken}&type=image";//上传临时素材 3天

        $json =curl($url,$strData);

        $arr=json_decode($json);
        return  $arr->media_id;
    }
    public function uploadImg($getToken,$imgFile,$name=null){//上传图片
        if(S($name)){
            return S($name);
        }else{
            $strData=array(
                'media'=>'@'.$imgFile
            );
            $url="https://api.weixin.qq.com/cgi-bin/media/upload?access_token={$getToken}&type=image";//上传临时素材 3天



            $json = curl($url,$strData);
            $arr=json_decode($json);
            if($arr->media_id){
                S($name,$arr->media_id,86400);
            }
            return  $arr->media_id;
        }
    }

    public function createMenu(){//创建公众号菜单
        $getToken=getToken();
        $data = [
            "button"=>[
                ["name"=>"热门测算","sub_button"=>[
                    ['type'=>"view","name"=>"八字精批","url"=>"http://wx1.zmweb.top/zhiming/index.php/Home-Bzjp-index?channel=gongzhonghao_2"],
                    ['type'=>"view","name"=>"八字合婚","url"=>"http://wx1.zmweb.top/zhiming/index.php/Home-Bzhh-index?channel=gongzhonghao_2"],
                    ['type'=>"view","name"=>"一生财运","url"=>"http://wx1.zmweb.top/zhiming/index.php/Home-Bzcy-index?channel=gongzhonghao_2"],
                    ['type'=>"view","name"=>"趣味测试","url"=>"http://wx1.zmweb.top/quce"],
                ]],
                ["name"=>"2020运势","sub_button"=>[
                    ['type'=>"view","name"=>"2020年运势","url"=>"http://wx1.zmweb.top/zhiming/index.php/Home-Lnyc2020-index?channel=gongzhonghao_2"],
                    ['type'=>"view","name"=>"一生运势","url"=>"http://wx1.zmweb.top/zhiming/index.php/Home-Zwds-index?channel=gongzhonghao_2"],
                    ['type'=>"view","name"=>"婚姻走势","url"=>"http://wx1.zmweb.top/zhiming/index.php/Home-Hyzs-index?channel=gongzhonghao_2"],
                    ['type'=>"view","name"=>"2020财运","url"=>"http://wx1.zmweb.top/zhiming/index.php/Home-Bzcy-index?channel=gongzhonghao_2"],
                ]],
                ["name"=>"我的订单","sub_button"=>[
                    ['type'=>"view","name"=>"我的订单","url"=>"http://wx1.zmweb.top/zhiming/index.php/Home-Index-mycesuan"],
                    ['type'=>"view","name"=>"领取红包","url"=>"http://android.myapp.com/myapp/detail.htm?apkName=com.mrkj.sm&ADTAG=mobile"],
                    ['type'=>"view","name"=>"今日运势","url"=>"http://wx1.zmweb.top/zhiming/index.php/Home-Mrys-index"],
                    ['type'=>"click","name"=>"个性签名","key"=>"个性签名"],
                    ['type'=>"miniprogram","name"=>"紫微命盘","url"=>"http://mp.weixin.qq.com", "appid"=>"wxbb86bd400ca5108b", "pagepath"=>"pages/edit/main"],
                ]],
            ]
        ];
//        ['type'=>"view","name"=>"我的订单","url"=>"https://www.yixueqm.com/zhiming/index.php/Home-Index-mycesuan"],
        $json = json_encode($data,JSON_UNESCAPED_UNICODE);
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$getToken}";

        $json = curl($url,$json);
        $jsonarr = json_decode($json,true);
        dump($jsonarr);
        if($jsonarr['errcode']==0){
            echo "<meta charset='utf-8'/>菜单创建成功";
        }else{
            echo "<meta charset='utf-8'/>菜单创建失败！";
            dump($jsonarr);
        }

    }

}